<?php

namespace App\Http\Controllers\Home;

use App\Http\Repository\MessageRepository;
use App\Http\Servers\Home\BaseServer;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class InfoController extends CommonController
{
    public function index(Request $request, BaseServer $baseServer, MessageRepository $messageRepository)
    {
        //本地访问不记录访问次数
        if (getIp() != '127.0.0.1') {
            \App\Info::where('id', $request->id)->increment('page_view');
        }

        $tmpChunk = \App\Chunk::where('path', $request->chunk)
            ->where('status', 1)
            ->get()
            ->toArray();
        $tmpChunk ? $data['chunk'] = $tmpChunk[0] : abort(404);

        $sorts = \App\InfoSortLines::where('info', $request->id)
            ->join('sorts', 'sorts.id', '=', 'info_sort_lines.sort')
            ->select(\DB::raw('concat("' . $data['chunk']['path'] . 'list_",sorts.id,".html") as url'), 'sorts.name')
            ->where('status', 1)
            ->get()
            ->toArray();
        (bool)$sorts ?: abort(404);

        $data['info'] = \App\Info::where('infos.status', 1)
            ->select('infos.*', 'infos.created_at as time')
            ->join('info_sort_lines', 'info_sort_lines.info', '=', 'infos.id')
            ->join('chunks', 'chunks.id', '=', 'info_sort_lines.chunk')
            ->where('chunks.path', $request->chunk)
            ->whereNull('set_time_out')
            ->findorfail($request->id)
            ->toArray();

        $data['info']['sorts'] = $sorts;
        $data['info']['filesize'] = calc(filesize('.' . $data['info']['file']));
        if ((bool)$data['info']['author_role']) {
            $data['info']['author'] = config('set.web_name') . '-' . \App\Admin::where('id', $data['info']['author'])->value('name');
        } else {
            $data['info']['author'] = '用户-' . \App\User::where('id', $data['info']['author'])->value('name');
        }

        $tmpImages = \App\InfoImageLines::where('info', $request->id)
            ->join('images', 'images.id', '=', 'info_image_lines.image')
            ->select('images.*')
            ->get()
            ->toArray();
        foreach ($tmpImages as $image) {
            $data['info']['images'][] = !empty($image['water']) ? $image['water'] : $image['path'];
        }

        //去除了分类
        $data['frames'] = $baseServer->frame([
            ['url' => route('sort_all', $request->chunk), 'name' => $data['chunk']['name']],
            ['url' => '', 'name' => subtext($data['info']['name'], 5)],
        ]);

        if (config('area')) {
            $data['title'] = $data['info']['name'] . '_' . config('set.web_name') . '_' . config('range')[config('area')] . '分站';
        } else {
            $data['title'] = $data['info']['name'] . '_' . config('set.web_name');
        }

        //生成关键词
        if ((bool)$data['chunk']['long_tail']) {
            $data['keywords'] = $baseServer->getLongKeywords($data['info']['name']);
        } else {
            $data['keywords'] = $data['info']['name'];
        }
        $data['keywords'] .= ',' . $data['info']['tag'];
        $baseServer->keywordDowork($request, $data['keywords']);

        $data['description'] = !empty($data['info']['simpledescribe']) ? $data['info']['simpledescribe'] : config('set.web_description');

        $tag = $data['info']['tag'];
        $data['links'] = \App\InfoSortLines::where('chunks.status', 1)
            ->where('sorts.status', 1)
            ->where('infos.status', 1)
            ->where('chunks.path', 'product')
            ->where(function ($query) use ($tag) {
                if (!empty($tag)) {
                    foreach (explode(',', $tag) as $tagport) {
                        $str[] = 'infos.tag like "%' . $tagport . '%"';
                    }
                    $query->whereRaw(implode(' or ', $str));
                }
            })
            ->where('infos.id', '<>', $request->id)
            ->join('infos', 'infos.id', '=', 'info_sort_lines.info')
            ->join('sorts', 'sorts.id', '=', 'info_sort_lines.sort')
            ->join('chunks', 'chunks.id', '=', 'info_sort_lines.chunk')
            ->leftjoin('info_image_lines', 'info_image_lines.info', '=', 'infos.id')
            ->leftjoin('images', 'images.id', '=', 'info_image_lines.image')
            ->select('infos.*', 'images.path as image', 'images.water', 'infos.created_at as time')
            ->groupBy('infos.id')
            ->orderBy('infos.xindex', 'DESC')
            ->take($data['chunk']['link_info_num'])
            ->get()
            ->toArray();
        foreach ($data['links'] as $k => $info) {
            $data['links'][$k]['image'] = !empty($info['water']) ? $info['water'] : $info['image'];
        }
        $data['linkNews'] = \App\InfoSortLines::where('chunks.status', 1)
            ->where('sorts.status', 1)
            ->where('infos.status', 1)
            ->where('chunks.path', 'new')
            ->where(function ($query) use ($tag) {
                if (!empty($tag)) {
                    foreach (explode(',', $tag) as $tagport) {
                        $str[] = 'infos.tag like "%' . $tagport . '%"';
                    }
                    $query->whereRaw(implode(' or ', $str));
                }
            })
            ->join('infos', 'infos.id', '=', 'info_sort_lines.info')
            ->join('sorts', 'sorts.id', '=', 'info_sort_lines.sort')
            ->join('chunks', 'chunks.id', '=', 'info_sort_lines.chunk')
            ->select('infos.*', 'infos.created_at as time')
            ->groupBy('infos.id')
            ->orderBy('infos.xindex', 'DESC')
            ->take($data['chunk']['link_info_num'])
            ->get()
            ->toArray();

        $ids = array_column(\Cache::get('share')['allInfos'][$request->chunk], 'id');
        $prevInfoIdKey = array_search($request->id, $ids) - 1;
        $nextInfoIdKey = array_search($request->id, $ids) + 1;
        if (!empty($ids[$prevInfoIdKey])) {
            $data['prev'] = \App\Info::leftjoin('info_image_lines', 'info_image_lines.info', '=', 'infos.id')
                ->leftjoin('images', 'images.id', '=', 'info_image_lines.image')
                ->select('infos.*', 'images.path as image', 'images.water')
                ->find($ids[$prevInfoIdKey])
                ->toArray();
            $data['prev']['image'] = !empty($data['prev']['water']) ? $data['prev']['water'] : $data['prev']['image'];
        } else {
            $data['prev'] = null;
        }
        if (!empty($ids[$nextInfoIdKey])) {
            $data['next'] = \App\Info::leftjoin('info_image_lines', 'info_image_lines.info', '=', 'infos.id')
                ->leftjoin('images', 'images.id', '=', 'info_image_lines.image')
                ->select('infos.*', 'images.path as image', 'images.water')
                ->find($ids[$nextInfoIdKey])
                ->toArray();
            $data['next']['image'] = !empty($data['next']['water']) ? $data['next']['water'] : $data['next']['image'];
        } else {
            $data['next'] = null;
        }

        //得到当前信息的评论/留言
        $data['messagelist'] = $messageRepository->getMessage(10, $request->id);

        if ((bool)config('set.wap_jump') && is_mobile()) {
            return view('home.m.' . config('set.wap_theme') . '.info.' . $data['info']['theme'], $data);
        }

        return view('home.pc.info.' . $data['info']['theme'], $data);
    }
}
